import * as XLSX from 'xlsx'

// 工厂模式 - 文件解析器工厂
export class FileParserFactory {
  static createParser(fileType) {
    switch (fileType) {
      case 'xlsx':
      case 'xls':
        return new ExcelParser()
      case 'csv':
        return new CsvParser()
      default:
        throw new Error('不支持的文件类型')
    }
  }
}

// 文件解析器基类
export class FileParser {
  parse(file, callback) {
    throw new Error('抽象方法，需要子类实现')
  }
  
  formatData(data) {
    throw new Error('抽象方法，需要子类实现')
  }
}

// Excel解析器
export class ExcelParser extends FileParser {
  parse(file, callback) {
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = e.target.result
        const workbook = XLSX.read(data, { type: 'array' })
        const firstSheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[firstSheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet)
        callback(this.formatData(jsonData))
      } catch (error) {
        console.error('Excel解析错误:', error)
        callback([])
      }
    }
    reader.readAsArrayBuffer(file)
  }
  
  formatData(data) {
    return data.map(item => ({
      studentId: item['学号'] || '',
      name: item['姓名'] || '',
      grade: item['年级'] || '',
      major: item['专业'] || ''
    }))
  }
}

// CSV解析器
export class CsvParser extends FileParser {
  parse(file, callback) {
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const csvData = e.target.result
        const lines = csvData.split('\n')
        const headers = lines[0].split(',')
        
        const result = []
        for (let i = 1; i < lines.length; i++) {
          if (!lines[i].trim()) continue
          
          const values = lines[i].split(',')
          const obj = {}
          
          headers.forEach((header, index) => {
            obj[header.trim()] = values[index] ? values[index].trim() : ''
          })
          
          result.push(obj)
        }
        
        callback(this.formatData(result))
      } catch (error) {
        console.error('CSV解析错误:', error)
        callback([])
      }
    }
    reader.readAsText(file)
  }
  
  formatData(data) {
    return data.map(item => ({
      studentId: item['学号'] || '',
      name: item['姓名'] || '',
      grade: item['年级'] || '',
      major: item['专业'] || ''
    }))
  }
} 